package com.example.myapp;

import androidx.appcompat.app.AppCompatActivity;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import java.util.HashMap;

public class PianoActivity extends AppCompatActivity implements View.OnClickListener{
    private SoundPool soundPool;
    private HashMap<Integer,Integer> map = new HashMap<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_piano);
        ImageView iv_do = (ImageView) findViewById(R.id.iv_do);
        ImageView iv_re = (ImageView) findViewById(R.id.iv_re);
        ImageView iv_mi = (ImageView) findViewById(R.id.iv_mi);
        ImageView iv_fa = (ImageView) findViewById(R.id.iv_fa);
        ImageView iv_so = (ImageView) findViewById(R.id.iv_so);
        ImageView iv_la = (ImageView) findViewById(R.id.iv_la);
        ImageView iv_si = (ImageView) findViewById(R.id.iv_si);
        iv_do.setOnClickListener(this);
        iv_re.setOnClickListener(this);
        iv_mi.setOnClickListener(this);
        iv_fa.setOnClickListener(this);
        iv_so.setOnClickListener(this);
        iv_la.setOnClickListener(this);
        iv_si.setOnClickListener(this);
        initSoundPool();
    }
    private void  initSoundPool() {
        if (soundPool == null) {
            soundPool = new SoundPool(7, AudioManager.STREAM_SYSTEM,0);
        }
        map.put(R.id.iv_do,soundPool.load(this,R.raw.music_do,1));
        map.put(R.id.iv_re,soundPool.load(this,R.raw.music_re,1));
        map.put(R.id.iv_mi,soundPool.load(this,R.raw.music_mi,1));
        map.put(R.id.iv_fa,soundPool.load(this,R.raw.music_fa,1));
        map.put(R.id.iv_so,soundPool.load(this,R.raw.music_so,1));
        map.put(R.id.iv_la,soundPool.load(this,R.raw.music_la,1));
        map.put(R.id.iv_si,soundPool.load(this,R.raw.music_si,1));
    }
    @Override
    public void onClick(View v){
        play(v.getId());
    }
    private void play(int i){
        soundPool.play(map.get(i),1.0f,1.0f,0,0,1.0f);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(soundPool != null) {
            soundPool.autoPause();
            soundPool.release();
            soundPool = null;
        }
    }
}